<template>
  <div class="flex-main">
    <el-input v-model="searchValue" placeholder="请输入角色名称" style="margin: 10px 0;">
      <template slot="append">
        <el-button type="primary" icon="el-icon-plus" @click="handleCreate">新增</el-button>
      </template>
    </el-input>
    <el-tree
      ref="roleTree"
      v-loading="treeLoading"
      class="common-el-tree tree-active"
      :data="roleTreeData"
      :props="defaultRoleProps"
      node-key="id"
      default-expand-all
      :expand-on-click-node="false"
      :current-node-key="selectedDataId"
      :filter-node-method="onTreeFilter"
      @node-click="handleRoleNodeClick">
      <span slot-scope="{ node}" class="custom-tree-node">
        <i v-if="node.data.pid!=='0'" class="el-icon-user" />
        <span v-if="node.data.pid==='0'" class="text" style="font-weight:bold;font-size: 14px;">{{ node.label }}</span>
        <span v-else class="text">{{ node.label }}</span>
        <span v-if="node.data.pid!=='0'">
          <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(node.data)" />
          <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemove(node.data)" />
        </span>
      </span>
    </el-tree>
    <!--新增/编辑对话框-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" @close="sideBox.recordShow=!sideBox.recordShow">
      <template slot="body">
        <el-form ref="dataForm" :rules="recordRules" :model="roleRecord" label-position="right" label-width="120px">
          <el-form-item label="角色编号:" prop="code">
            <el-input v-model="roleRecord.code" :disabled="sideBox.status === 'update'" maxlength="20" show-word-limit placeholder="请输入角色编号" />
          </el-form-item>
          <el-form-item label="角色名称:" prop="name">
            <el-input v-model="roleRecord.name" maxlength="20" show-word-limit placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="数据范围:" prop="dataScope">
            <el-select v-model="roleRecord.dataScope" style="width:100%">
              <el-option
                v-for="item in dataScopeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="所属上级:" prop="pid">
            <el-select v-model="roleRecord.pid" disabled placeholder="请选择所属上级" filterable style="width:100%">
              <el-option
                v-for="item in roleTreeData"
                :key="item.id"
                :label="item.name"
                :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="角色描述:" prop="description">
            <el-input v-model="roleRecord.description" :rows="4" type="textarea" maxlength="300" show-word-limit />
          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status === 'create' ? createData() : updateData()">保存</el-button>
      </template>
    </side-box>

  </div>
</template>
<script>
export default {
  props: {
    dataScopeOptions: {
      type: Array,
      required: true

    }
  },
  data() {
    return {
      searchValue: '',
      defaultRoleProps: {
        children: 'children',
        label: 'name'
      },
      roleTreeData: [],
      treeLoading: false,
      selectedDataId: '',
      selectedTreeNode: {},
      selectedTreeData: {},
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create' // 对话框状态
      },

      roleRecord: {
        code: '',
        name: '',
        pid: '',
        basePath: '',
        description: '',
        icon: '',
        roleLevel: ''
      },
      recordRules: {
        code: [
          { required: true, message: '请输入角色编号', trigger: 'blur' },
          { validator: this.commonValidate.validateEngOrNum, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入角色标题', trigger: 'blur' }
        ],
        pid: [
          { required: true, message: '请选择上级所属', trigger: 'blur' }
        ],
        dataScope: [
          { required: true, message: '请选择数据范围', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    searchValue: function(val) {
      this.$refs.roleTree.filter(val)
    }
  },
  created() {
    this.roleTree()
  },
  methods: {
    async roleTree() {
      this.treeLoading = true
      this.roleTreeData = []
      const response = await this.$store.dispatch('roleTreeTable', { })
      this.roleTreeData = response
      if (this.roleTreeData.length > 0) {
        if (this.roleTreeData[0].children.length > 0) {
          var selectId = this.roleTreeData[0].children[0].id
          this.$refs.roleTree.setCheckedKeys([selectId])
          this.$nextTick(() => {
            this.handleRoleNodeClick(this.roleTreeData[0].children[0], this.$refs.roleTree.getNode(selectId))
          })
        }
      }
      this.treeLoading = false
    },
    /* 节点过滤函数 */
    onTreeFilter(value, data) {
      if (!value) return true
      return data[this.defaultRoleProps.filter] ? data[this.defaultRoleProps.label].indexOf(value) !== -1 || data[this.defaultRoleProps.filter].indexOf(value.toUpperCase()) !== -1 : data[this.defaultRoleProps.label].indexOf(value) !== -1
    },
    // 单击角色
    handleRoleNodeClick(data, node) {
      if (node.level === 1) {
        if (this.selectedTreeData) {
          this.$nextTick(() => {
            this.$refs.roleTree.setCurrentKey(this.selectedTreeData.id)
          })
        }

        return
      }
      this.selectedTreeNode = node
      this.selectedTreeData = data
      this.selectedDataId = data.id
      this.$emit('selectedRole', data)
      this.$nextTick(() => {
        this.$refs.roleTree.setCurrentKey(data.id)
      })
    },
    /* 新增*/
    handleCreate() {
      this.roleRecord = {
        pid: this.selectedTreeData.pid,
        dataScope: 7
      }
      this.sideBox = {
        status: 'create',
        recordShow: true,
        title: '新增角色'
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('roleSave', this.roleRecord).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('创建成功')
            if (this.selectedTreeData) {
              this.selectedTreeNode.parent.data.children.push(response)
              this.selectedTreeData = response
              this.$emit('selectedRole', response)
            } else {
              this.roleTree()
            }
          }).catch(() => {
          })
        }
      })
    },

    /* 编辑*/
    handleUpdate(row) {
      this.roleRecord = Object.assign({}, row) // copy obj
      this.sideBox = {
        title: '编辑[' + this.roleRecord.name + ']角色',
        status: 'update',
        recordShow: true
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          delete this.roleRecord.children
          const tempData = Object.assign({}, this.roleRecord)
          this.$store.dispatch('roleUpdate', tempData).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('编辑成功')
            this.$set(this.selectedTreeData, 'name', response.name)
            this.$emit('selectedRole', response)
          }).catch((_) => {
          })
        }
      })
    },
    handleRemove(row) {
      if (row.isDefault === 1) {
        this.msgWarning('内置数据,无权删除')
        return
      }
      this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('roleRemove', [row.id]).then(response => {
          this.msgSuccess('删除成功!')
          this.roleTree()
        }).catch(() => {})
      }).catch(() => { })
    }
  }
}
</script>
